package com.cccyy.data;

public class LuhnAlgorithm {
    //    借记卡最后一位校验位数字生成
    public static void main(String[] args) {
        String cardNumberWithoutCheckDigit = "623565665552023045"; // 示例卡号，不包含最后一位验证数字
        int checkDigit = generateCheckDigit(cardNumberWithoutCheckDigit);
        String cardNumberWithCheckDigit = cardNumberWithoutCheckDigit + checkDigit;

        System.out.println("生成的借记卡号：" + cardNumberWithCheckDigit);
//        生成的借记卡号：6235656655520230457

        String s = generateCheckDigitWithOld(cardNumberWithoutCheckDigit);
        System.out.println("生成的借记卡号-OLD：" + s);
        //62356566555202304572
    }

    public static int generateCheckDigit(String cardNumber) {
        int sum = 0;
        boolean shouldDouble = false;
        for (int i = cardNumber.length() - 1; i >= 0; i--) {
            int digit = Integer.parseInt(cardNumber.substring(i, i + 1));
            if (shouldDouble) {
                digit *= 2;
                if (digit > 9) {
                    digit -= 9;
                }
            }
            sum += digit;
            shouldDouble = !shouldDouble;
        }
        return (10 - (sum % 10)) % 10;
    }

    public static String generateCheckDigitWithOld(String cardNumber) {
        char[] cn = cardNumber.toCharArray();
        final int tableLuhnMod10[][] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 2, 4, 6, 8, 1, 3, 5, 7, 9}};
        int odd = 0;
        int sum = 0;
        for (int i = cn.length - 1; i >= 0; i--) {
            if (Character.isDigit(cn[i])) {
                sum += tableLuhnMod10[(odd = 1 - odd)][cn[i] - '0'];
            }
            sum %= 10;
        }
        return cardNumber + (char) (0x30 + (sum > 0 ? 10 - sum : 0));
    }
}
